
//add formhtml() to update inner html with new values inserted in the text boxes
(function($) {
  var oldHTML = $.fn.html;

  $.fn.formhtml = function() {
    if (arguments.length) return oldHTML.apply(this,arguments);
    $("input,button", this).each(function() {
      this.setAttribute('value',this.value);
    });
    $("textarea", this).each(function() {
      
      $(this).text(this.value);
    });
    $("input:radio,input:checkbox", this).each(function() {
      // im not really even sure you need to do this for "checked"
      // but what the heck, better safe than sorry
      if (this.checked) this.setAttribute('checked', 'checked');
      else this.removeAttribute('checked');
    });
    $("option", this).each(function() {
      // also not sure, but, better safe...
      if (this.selected) this.setAttribute('selected', 'selected');
      else this.removeAttribute('selected');
    });
    return oldHTML.apply(this);
  };

  //optional to override real .html() if you want
  // $.fn.html = $.fn.formhtml;
})(jQuery);
$(document).ready(function()
{
    
    $('#saveMessage').hide();
    $('.sortable').nestedSortable({
        handle: 'div',
        items: 'li',
        tolerance: 'pointer',
        toleranceElement: '> div',
        maxLevels: 2,
    });
    $.ajax(
            {
                type: "POST",
                url: baseUrl + "/administration/menu/load",
                success: function(data) {
                    $('.sortable.ui-sortable').html(data);
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    alert(xhr.status);
                    alert(xhr.responseText);
                    alert(thrownError);
                }
                
        });
    
    $('#save').click(function(e) {
        children = $('.sortable.ui-sortable').children();
        var array = [];
        var pagesArray =  [];
        children.each(function(index) {

            if ($(this).prop("tagName") == "LI") {
                
                liChildren = $(this).children();
                liChildren.each(function(index) {
                    if ($(this).prop("tagName") == "OL") {
                        olChildren = $(this).children();
                        
                        olChildren.each(function(index) {
                            if ($(this).prop("tagName") == "LI") {
                                idArray = $(this).attr('id').split("_");
                                id = idArray.pop();
                                //get Name and URI
                                navLabel = $("#navLabel_" + id).val();
                                navUri = $("#uri_" + id).val();
                                pagesArray.push({"navLabel": navLabel, "navUri": navUri});
                                }
                        })
                    }
                })
                                idArray = $(this).attr('id').split("_");
                                id = idArray.pop();
                                //get Name and URI
                                navLabel = $("#navLabel_" + id).val();
                                navUri = $("#uri_" + id).val();
                                if( pagesArray.length > 0){
                                    array.push({"navLabel": navLabel, "navUri": navUri, pages: pagesArray});
                                    pagesArray = [];
                                } else {
                                    array.push({"navLabel": navLabel, "navUri": navUri});
                                }
                
            }
        })
        innerhtml = $('.sortable.ui-sortable').formhtml();
        $.post(baseUrl + "/administration/menu/save/", {json: JSON.stringify(array), html: innerhtml}, function(data){console.log(data)});
        $('#saveMessage').hide();
        $('#saveMessage').show();

    });
    
    $("#addPages").click(function() {
        getValueUsingParentTag('pagesItems','page','page','view');

    });
    
    
    $("#addArticles").click(function() {
        getValueUsingParentTag('ArticlesItems','article','news','view');

    });
    
    
    $("#addCategories").click(function() {
        getValueUsingParentTag('categoriesItems','category','news','category');

    });
    
    
    $("#addLinks").click(function() {
       addLink();

    });

});

function addLink() {
    var $randId = makeId();
    $(".sortable.ui-sortable").append('<li id="li_' + $randId + '">\n\
<div>\n\
<div class="panel panel-default">\n\
<div class="panel-heading">\n\
<h4 class="panel-title">\n\
<a data-toggle="collapse" data-parent="#menuItems" href="#collapse' + $randId + '">' + $("#linkLabel").val() + '<\a>\n\
</a>\n\
</h4>\n\
</div>\n\
<div id="collapse' + $randId + '" class="panel-collapse collapse">\n\
<div class="panel-body">\n\
<div class="form-group">\n\
<label for="navLabel_' + $randId + '">Navigation Label</label>\n\
<input type="text" class="form-control" id="navLabel_' + $randId + '" value="' + $("#linkLabel").val() + '"/>\n\
<label for="uri_' + $randId + '">URL</label>\n\
<input type="text"  class="form-control" id="uri_' + $randId + '" value="'+$("#link").val() + '"/>\n\
<\div>\n\
<button id="btn' + $randId + '" type="button" class="btn btn-link" onclick="removeItem(' + "'" + $randId + "'" + ')">Remove</button>\n\
</div>\n\
</div>\n\
</div>\n\
</div>\n\
</li>');
}

function getValueUsingParentTag(parrent,type,controller,action) {
    var chkArray = [];

    /* look for all checkboes that have a parent id called 'checkboxlist' attached to it and check if it was checked */
    $("."+parrent+" input:checked").each(function() {
        chkArray.push($(this).val());
    });
    
    


    /* check if there is selected checkboxes, by default the length is 1 as it contains one single comma */
    if (chkArray.length > 0) {
        for (var $i = 0; $i < chkArray.length; $i++) {
            var $randId = makeId();
            $(".sortable.ui-sortable").append('<li id="li_' + $randId + '">\n\
<div>\n\
<div class="panel panel-default">\n\
<div class="panel-heading">\n\
<h4 class="panel-title">\n\
<a data-toggle="collapse" data-parent="#menuItems" href="#collapse' + $randId + '">' + $("#"+type+"_" + chkArray[$i]).parent().text() + '<\a>\n\
</a>\n\
</h4>\n\
</div>\n\
<div id="collapse' + $randId + '" class="panel-collapse collapse">\n\
<div class="panel-body">\n\
<div class="form-group">\n\
<label for="navLabel_' + $randId + '">Navigation Label</label>\n\
<input type="text" class="form-control" id="navLabel_' + $randId + '" value="' + $("#"+type+"_" + chkArray[$i]).parent().text() + '"/>\n\
<input type="hidden"  id="uri_' + $randId + '" value="'+controller+'/'+action+'/id/' + $("#"+type+"_" + chkArray[$i]).val() + '"/>\n\
<\div>\n\
<button id="btn' + $randId + '" type="button" class="btn btn-link" onclick="removeItem(' + "'" + $randId + "'" + ')">Remove</button>\n\
</div>\n\
</div>\n\
</div>\n\
</div>\n\
</li>'
                    );
        }
    } else {
        alert("Please at least one item");
    }
}
function removeItem($rand) {

    $("#btn" + $rand).closest('li').remove();
}
//generate random id for accordion divs
function makeId()
{
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    for (var i = 0; i < 5; i++)
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}

